<template>
  <div class="manus-app">
    <div class="chat-container">
      <!-- 头部 -->
      <div class="chat-header">
        <div class="header-left">
          <button class="back-btn" @click="goBack">
            <span>←</span> 返回
          </button>
          <h2>🤖 AI 超级智能体</h2>
        </div>
        <div class="header-right">
          <span class="status" :class="{ 'connected': isConnected }">
            {{ isConnected ? '已连接' : '未连接' }}
          </span>
        </div>
      </div>

      <!-- 聊天记录区域 -->
      <div class="chat-messages" ref="messagesContainer">
        <!-- 欢迎消息 -->
        <div class="message ai welcome-message">
          <div class="message-avatar">
            <span>🤖</span>
          </div>
          <div class="message-content">
            <div class="message-text">
              你好！我是 AI 超级智能体 🤖 我可以帮助你解决各种问题，包括知识问答、任务处理、数据分析等。请告诉我你需要什么帮助，我会尽力为你提供解决方案。
            </div>
            <div class="message-time">{{ formatTime(new Date()) }}</div>
          </div>
        </div>
        
        <!-- 消息列表 -->
        <div 
          v-for="(message, index) in messages" 
          :key="index"
          :class="['message', message.type]"
        >
          <div class="message-avatar">
            <span v-if="message.type === 'ai'">🤖</span>
            <span v-else>👤</span>
          </div>
          <div class="message-content">
            <div class="message-text" v-html="formatMessage(message.content)"></div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="isLoading" class="message ai">
          <div class="message-avatar">🤖</div>
          <div class="message-content">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input">
        <div class="input-container">
          <textarea
            v-model="inputMessage"
            @keydown.enter.prevent="sendMessage"
            placeholder="输入您的问题或任务..."
            :disabled="isLoading"
            ref="messageInput"
          ></textarea>
          <button 
            @click="sendMessage" 
            :disabled="!inputMessage.trim() || isLoading"
            class="send-btn"
          >
            <span v-if="!isLoading">发送</span>
            <span v-else>发送中...</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { connectManusSSE } from '../services/api.js'

export default {
  name: 'ManusApp',
  data() {
    return {
      messages: [],
      inputMessage: '',
      isLoading: false,
      isConnected: false,
      eventSource: null
    }
  },
  mounted() {
    // 移除自动添加欢迎消息的逻辑
    this.scrollToBottom()
  },
  methods: {
    goBack() {
      this.$router.push('/')
    },
    
    async sendMessage() {
      if (!this.inputMessage.trim() || this.isLoading) return
      
      // 关闭之前的连接
      if (this.eventSource) {
        this.eventSource.close()
        this.eventSource = null
      }
      
      const userMessage = this.inputMessage.trim()
      this.inputMessage = ''
      
      // 添加用户消息
      this.messages.push({
        type: 'user',
        content: userMessage,
        timestamp: new Date()
      })
      
      this.isLoading = true
      this.scrollToBottom()
      
      let aiResponse = ''
      let isCompleted = false
      
      // 设置超时定时器
      const timeoutId = setTimeout(() => {
        console.log('Manus SSE 连接超时')
        if (this.eventSource) {
          this.eventSource.close()
        }
        this.addErrorMessage('连接超时，请检查网络或稍后重试')
        this.isLoading = false
        this.isConnected = false
      }, 30000) // 30秒超时
      
      try {
        this.eventSource = connectManusSSE(
          userMessage,
          (data) => {
            clearTimeout(timeoutId) // 清除超时定时器
            aiResponse += data
            this.updateLastMessage(aiResponse)
            this.isConnected = true
          },
          (error) => {
            clearTimeout(timeoutId) // 清除超时定时器
            console.error('SSE 错误:', error)
            // 不显示连接失败的错误消息
            this.isLoading = false
            this.isConnected = false
          },
          () => {
            clearTimeout(timeoutId) // 清除超时定时器
            isCompleted = true
            // 标记最后一条 AI 消息为完成
            const lastAiMessage = this.messages.find(msg => msg.type === 'ai' && !msg.isComplete)
            if (lastAiMessage) {
              lastAiMessage.isComplete = true
            }
            this.isLoading = false
            this.scrollToBottom()
          }
        )
      } catch (error) {
        clearTimeout(timeoutId) // 清除超时定时器
        console.error('发送消息错误:', error)
        this.addErrorMessage('发送失败，请稍后重试')
        this.isLoading = false
        this.isConnected = false
      }
    },
    
    updateLastMessage(content) {
      // 查找最后一条 AI 消息或创建新的
      let lastAiMessage = this.messages.find(msg => msg.type === 'ai' && !msg.isComplete)
      
      if (!lastAiMessage) {
        lastAiMessage = {
          type: 'ai',
          content: content,
          timestamp: new Date(),
          isComplete: false
        }
        this.messages.push(lastAiMessage)
      } else {
        lastAiMessage.content = content
      }
      
      this.scrollToBottom()
    },
    
    addErrorMessage(message = '抱歉，我遇到了一些问题。请稍后再试，或者检查网络连接。') {
      this.messages.push({
        type: 'ai',
        content: message,
        timestamp: new Date()
      })
    },
    
    formatMessage(content) {
      // 简单的换行处理
      return content.replace(/\n/g, '<br>')
    },
    
    formatTime(timestamp) {
      const date = new Date(timestamp)
      return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer
        if (container) {
          container.scrollTop = container.scrollHeight
        }
      })
    }
  },
  
  beforeUnmount() {
    if (this.eventSource) {
      this.eventSource.close()
    }
  }
}
</script>

<style scoped>
.manus-app {
  height: 100vh;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.chat-container {
  width: 100%;
  max-width: 800px;
  height: 100%;
  max-height: 800px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-header {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.back-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  padding: 8px 15px;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.header-left h2 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
}

.status {
  font-size: 0.9rem;
  opacity: 0.8;
  padding: 4px 12px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.2);
}

.status.connected {
  background: rgba(76, 175, 80, 0.2);
  color: #4caf50;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.message {
  display: flex;
  gap: 12px;
  max-width: 80%;
  animation: fadeInUp 0.3s ease-out;
}

.message.user {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message.ai {
  align-self: flex-start;
}

.welcome-message {
  margin-bottom: 10px;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  flex-shrink: 0;
}

.message.user .message-avatar {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.message.ai .message-avatar {
  background: #f0f2f5;
}

.message-content {
  flex: 1;
}

.message-text {
  background: #f0f2f5;
  padding: 12px 16px;
  border-radius: 18px;
  line-height: 1.5;
  word-wrap: break-word;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.message.user .message-text {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  box-shadow: 0 2px 8px rgba(79, 172, 254, 0.3);
}

.message-time {
  font-size: 0.8rem;
  color: #999;
  margin-top: 5px;
  text-align: right;
}

.message.user .message-time {
  text-align: left;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 12px 16px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #999;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) { animation-delay: -0.32s; }
.typing-indicator span:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing {
  0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; }
  40% { transform: scale(1); opacity: 1; }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.chat-input {
  padding: 20px;
  border-top: 1px solid #eee;
  background: white;
}

.input-container {
  display: flex;
  gap: 10px;
  align-items: flex-end;
}

.input-container textarea {
  flex: 1;
  border: 2px solid #eee;
  border-radius: 20px;
  padding: 12px 16px;
  resize: none;
  font-family: inherit;
  font-size: 14px;
  line-height: 1.4;
  max-height: 100px;
  transition: border-color 0.3s;
}

.input-container textarea:focus {
  outline: none;
  border-color: #4facfe;
}

.input-container textarea:disabled {
  background: #f9f9f9;
  cursor: not-allowed;
}

.send-btn {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 20px;
  cursor: pointer;
  font-weight: 600;
  transition: all 0.3s;
  white-space: nowrap;
}

.send-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(79, 172, 254, 0.3);
}

.send-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

@media (max-width: 768px) {
  .manus-app {
    padding: 10px;
  }
  
  .chat-container {
    border-radius: 15px;
  }
  
  .message {
    max-width: 90%;
  }
  
  .header-left h2 {
    font-size: 1.2rem;
  }
}
</style>
